package com.apkicon.test;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 前景图片颜色分析器
 * 分析test.apk前景图片的实际颜色
 */
public class ForegroundColorAnalyzer {
    
    public static void main(String[] args) {
        try {
            System.out.println("Analyzing Foreground Color from test.apk");
            System.out.println("=========================================");
            
            // 加载前景图片
            File foregroundFile = new File("foreground_original.png");
            if (!foregroundFile.exists()) {
                System.err.println("Foreground file not found: " + foregroundFile.getName());
                return;
            }
            
            BufferedImage foreground = ImageIO.read(foregroundFile);
            if (foreground == null) {
                System.err.println("Failed to load foreground image");
                return;
            }
            
            System.out.println("Foreground Image Info:");
            System.out.println("  Size: " + foreground.getWidth() + "x" + foreground.getHeight());
            System.out.println("  Type: " + getImageType(foreground));
            System.out.println();
            
            // 分析颜色
            analyzeColors(foreground);
            
            // 分析透明度
            analyzeTransparency(foreground);
            
            // 分析主要颜色
            analyzeDominantColors(foreground);
            
            // 创建颜色测试图片
            createColorTestImages(foreground);
            
        } catch (Exception e) {
            System.err.println("Analysis failed: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    private static String getImageType(BufferedImage image) {
        switch (image.getType()) {
            case BufferedImage.TYPE_INT_RGB: return "RGB";
            case BufferedImage.TYPE_INT_ARGB: return "ARGB";
            case BufferedImage.TYPE_INT_ARGB_PRE: return "ARGB_PRE";
            case BufferedImage.TYPE_4BYTE_ABGR: return "4BYTE_ABGR";
            case BufferedImage.TYPE_4BYTE_ABGR_PRE: return "4BYTE_ABGR_PRE";
            case BufferedImage.TYPE_3BYTE_BGR: return "3BYTE_BGR";
            case BufferedImage.TYPE_BYTE_GRAY: return "BYTE_GRAY";
            case BufferedImage.TYPE_USHORT_GRAY: return "USHORT_GRAY";
            case BufferedImage.TYPE_BYTE_BINARY: return "BYTE_BINARY";
            case BufferedImage.TYPE_BYTE_INDEXED: return "BYTE_INDEXED";
            default: return "UNKNOWN (" + image.getType() + ")";
        }
    }
    
    private static void analyzeColors(BufferedImage image) {
        System.out.println("Color Analysis:");
        System.out.println("===============");
        
        int width = image.getWidth();
        int height = image.getHeight();
        
        // 分析中心区域
        int centerX = width / 2;
        int centerY = height / 2;
        int sampleSize = Math.min(width, height) / 4;
        
        System.out.println("Center Region (" + centerX + "," + centerY + "):");
        for (int y = centerY - sampleSize/2; y < centerY + sampleSize/2; y += sampleSize/4) {
            for (int x = centerX - sampleSize/2; x < centerX + sampleSize/2; x += sampleSize/4) {
                if (x >= 0 && x < width && y >= 0 && y < height) {
                    int rgb = image.getRGB(x, y);
                    int alpha = (rgb >> 24) & 0xFF;
                    int red = (rgb >> 16) & 0xFF;
                    int green = (rgb >> 8) & 0xFF;
                    int blue = rgb & 0xFF;
                    
                    System.out.printf("  [%d,%d]: #%08X RGB(%d,%d,%d) Alpha:%d\n", 
                                    x, y, rgb, red, green, blue, alpha);
                }
            }
        }
        
        // 分析四个角
        System.out.println("\nCorner Analysis:");
        int[][] corners = {{0, 0}, {width-1, 0}, {0, height-1}, {width-1, height-1}};
        for (int[] corner : corners) {
            int rgb = image.getRGB(corner[0], corner[1]);
            int alpha = (rgb >> 24) & 0xFF;
            int red = (rgb >> 16) & 0xFF;
            int green = (rgb >> 8) & 0xFF;
            int blue = rgb & 0xFF;
            
            System.out.printf("  Corner [%d,%d]: #%08X RGB(%d,%d,%d) Alpha:%d\n", 
                            corner[0], corner[1], rgb, red, green, blue, alpha);
        }
    }
    
    private static void analyzeTransparency(BufferedImage image) {
        System.out.println("\nTransparency Analysis:");
        System.out.println("=====================");
        
        int width = image.getWidth();
        int height = image.getHeight();
        int transparentPixels = 0;
        int opaquePixels = 0;
        int semiTransparentPixels = 0;
        
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int rgb = image.getRGB(x, y);
                int alpha = (rgb >> 24) & 0xFF;
                
                if (alpha == 0) {
                    transparentPixels++;
                } else if (alpha == 255) {
                    opaquePixels++;
                } else {
                    semiTransparentPixels++;
                }
            }
        }
        
        int totalPixels = width * height;
        System.out.println("Total pixels: " + totalPixels);
        System.out.println("Transparent pixels: " + transparentPixels + " (" + (transparentPixels * 100 / totalPixels) + "%)");
        System.out.println("Opaque pixels: " + opaquePixels + " (" + (opaquePixels * 100 / totalPixels) + "%)");
        System.out.println("Semi-transparent pixels: " + semiTransparentPixels + " (" + (semiTransparentPixels * 100 / totalPixels) + "%)");
    }
    
    private static void analyzeDominantColors(BufferedImage image) {
        System.out.println("\nDominant Color Analysis:");
        System.out.println("========================");
        
        Map<Integer, Integer> colorCount = new HashMap<>();
        int width = image.getWidth();
        int height = image.getHeight();
        
        // 统计颜色
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int rgb = image.getRGB(x, y);
                int alpha = (rgb >> 24) & 0xFF;
                
                // 只统计非透明像素
                if (alpha > 0) {
                    colorCount.put(rgb, colorCount.getOrDefault(rgb, 0) + 1);
                }
            }
        }
        
        // 找出最常见的颜色
        System.out.println("Most common colors:");
        colorCount.entrySet().stream()
            .sorted((e1, e2) -> Integer.compare(e2.getValue(), e1.getValue()))
            .limit(10)
            .forEach(entry -> {
                int rgb = entry.getKey();
                int count = entry.getValue();
                int alpha = (rgb >> 24) & 0xFF;
                int red = (rgb >> 16) & 0xFF;
                int green = (rgb >> 8) & 0xFF;
                int blue = rgb & 0xFF;
                
                System.out.printf("  #%08X RGB(%d,%d,%d) Alpha:%d - %d pixels\n", 
                                rgb, red, green, blue, alpha, count);
            });
    }
    
    private static void createColorTestImages(BufferedImage originalForeground) {
        System.out.println("\nCreating Color Test Images:");
        System.out.println("============================");
        
        try {
            // 测试1: 提取主要颜色并创建纯色图片
            int dominantColor = findDominantColor(originalForeground);
            BufferedImage solidColor = new BufferedImage(512, 512, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = solidColor.createGraphics();
            g2d.setColor(new Color(dominantColor, true));
            g2d.fillRect(0, 0, 512, 512);
            g2d.dispose();
            
            ImageIO.write(solidColor, "PNG", new File("test_dominant_color.png"));
            System.out.println("✅ Dominant color test: test_dominant_color.png");
            
            // 测试2: 创建蓝色对比图片
            BufferedImage blueTest = new BufferedImage(512, 512, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d2 = blueTest.createGraphics();
            g2d2.setColor(Color.BLUE);
            g2d2.fillRect(0, 0, 512, 512);
            g2d2.dispose();
            
            ImageIO.write(blueTest, "PNG", new File("test_blue_reference.png"));
            System.out.println("✅ Blue reference test: test_blue_reference.png");
            
            // 测试3: 放大原始前景图片
            BufferedImage enlarged = new BufferedImage(512, 512, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d3 = enlarged.createGraphics();
            g2d3.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
            g2d3.drawImage(originalForeground, 0, 0, 512, 512, null);
            g2d3.dispose();
            
            ImageIO.write(enlarged, "PNG", new File("test_foreground_enlarged_512.png"));
            System.out.println("✅ Enlarged foreground: test_foreground_enlarged_512.png");
            
        } catch (IOException e) {
            System.err.println("Failed to create test images: " + e.getMessage());
        }
    }
    
    private static int findDominantColor(BufferedImage image) {
        Map<Integer, Integer> colorCount = new HashMap<>();
        int width = image.getWidth();
        int height = image.getHeight();
        
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int rgb = image.getRGB(x, y);
                int alpha = (rgb >> 24) & 0xFF;
                
                if (alpha > 0) {
                    colorCount.put(rgb, colorCount.getOrDefault(rgb, 0) + 1);
                }
            }
        }
        
        return colorCount.entrySet().stream()
            .max((e1, e2) -> Integer.compare(e1.getValue(), e2.getValue()))
            .map(Map.Entry::getKey)
            .orElse(0xFF000000); // Default to black if no color found
    }
}
